<template>
  <MainPage activeMenu="/shop"> 
    <el-container>
      <el-main>
        <div class="productList">
          <div class="productList_box">
            <div class="category_list">
              <span @click="categoryChange(index)" :class="{'active': activeIndex === index}" v-for="(category, index) in categoryList" :key="index" class="category">{{ category.name }}</span>
            </div>
            <div class="product_box">
              <el-row>
                <el-col :span="6" v-for="(product, index) in filteredProducts" :key="index" class="product_col">
                  <div class="item">
                    <img :src="getImageUrl(product.productId)" @click="detail(product)" alt="图片加载出错" class="cover">
                    <div class="information">
                      <span>{{ product.name }}</span>
                      
                    </div>
                    <div class="information">
                      <el-tag type="primary" style="font-size: 1rem;">{{ product.price }}元</el-tag>
                      <el-tooltip effect="light" content="加入购物车" placement="right">
                        <el-button type="primary" @click="openAddToCartDialog(product)" size="default"><el-icon><ShoppingCart /></el-icon></el-button>
                      </el-tooltip>
                    </div>
                    <br/>
                    <el-tooltip effect="light" content="立即购买" placement="right">
                      <el-button type="primary" @click="pay(product)" size="large" :auto-insert-space="true">立 即 购 买</el-button>
                    </el-tooltip>
                  </div>
                </el-col>
              </el-row>
            </div>
            <el-pagination class="pagination" :current-page="page.currentPage" :page-sizes="[8, 16, 24]" :page-size="page.pageSize" @size-change="handleSizeChange" @current-change="handleCurrentChange" layout="prev, pager, next, jumper, ->, sizes, total" :total="filteredProducts.length"></el-pagination>
          </div>
        </div>
      </el-main>
    </el-container>

    <!-- 加入购物车对话框 -->
    <el-dialog title="加入购物车" v-model="dialogVisible" width="30%">
      <span>商品名称: {{ selectedProduct.name }}</span>
      <el-input-number v-model="quantity" :min="1" :max="100" style="margin-top: 20px;"></el-input-number>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addToCart">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </MainPage>
</template>

<script>
import axios from '../../axios/axios';
import MainPage from '../Component/MainPage.vue';

export default {
  name: 'ProductList',
  components: { MainPage },
  data() {
    return {
      allProducts: [],
      productPage: [],
      page: {
        currentPage: 1,
        pageSize: 8, // 设置默认的 pageSize
        total: 0,
      },
      activeIndex: 0,
      categoryList: [], // 初始化为空数组
      dialogVisible: false,
      selectedProduct: {}, // 确保这是一个对象
      quantity: 1,
      imageUrls: new Map(), // 存储图片 URL 映射
    };
  },
  computed: {
    filteredProducts() {
      if (this.activeIndex === 0 || !this.categoryList[this.activeIndex].categoryId) {
        return this.allProducts.slice((this.page.currentPage - 1) * this.page.pageSize, this.page.currentPage * this.page.pageSize);
      }
      const categoryId = this.categoryList[this.activeIndex].categoryId;
      return this.allProducts.filter(product => product.categoryId === categoryId).slice((this.page.currentPage - 1) * this.page.pageSize, this.page.currentPage * this.page.pageSize);
    },
  },
  methods: {
    async fetchProducts(pageNum = 1) {
      try {
        console.log(`Fetching products with pageNum=${pageNum}, pageSize=${this.page.pageSize}`); // 调试信息
        const response = await axios.get('/product/page', {
          params: {
            pageSize: this.page.pageSize, // 请求当前页大小
            pageNum: pageNum, // 请求第一页
          },
        });

        if (Array.isArray(response.records)) {
          this.allProducts = response.records.map(product => ({
            ...product,
            img: null // 初始化 img 为 null
          }));

          // 获取所有产品的图片
          for (const product of this.allProducts) {
            await this.fetchImage(product.productId);
          }

          this.page.total = response.total;
          this.updateProductPage();
          console.log('Fetched products:', this.allProducts); // 调试信息
        } else {
          console.error('响应数据格式不正确:', response);
        }
      } catch (error) {
        console.error('获取商品列表失败', error);
      }
    },
    async fetchCategories() {
      try {
        const response = await axios.get('/admin/category');
        if (Array.isArray(response)) {
          this.categoryList = [{ categoryId: null, name: '全部分类' }, ...response]; // 将“全部分类”作为第一个选项
          console.log('Fetched categories:', response); // 调试信息
        } else {
          console.error('响应数据格式不正确:', response);
        }
      } catch (error) {
        console.error('获取类目列表失败', error);
      }
    },
    updateProductPage() {
      this.productPage = this.filteredProducts;
    },
    handleSizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.fetchProducts(this.page.currentPage); // 重新获取产品列表
    },
    handleCurrentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.updateProductPage(); // 更新产品页面
    },
    categoryChange(index) {
      this.activeIndex = index;
      console.log(`Category changed to index=${index}, categoryId=${this.categoryList[index].categoryId}`); // 调试信息
      this.updateProductPage(); // 更新产品页面
    },
    detail(product) {
      this.$router.push({ path: '/product', query: { id: product.productId } });
      this.$store.commit('DETAIL', product);
    },
    openAddToCartDialog(product) {
      this.selectedProduct = product; // 确保正确赋值
      this.dialogVisible = true;
    },
    async addToCart() {
      if (!this.selectedProduct || !this.selectedProduct.productId) {
        console.error('Selected product or product ID is undefined');
        this.$message({
          type: 'error',
          message: '请选择有效的商品',
        });
        return;
      }

      try {
        const data = await axios.post('/carts/add/cart', {
          product_id: this.selectedProduct.productId,
          count: this.quantity,
        });

        console.log('Response data:', data); // 调试信息

        if (data === true) {
          this.$message({
            type: 'success',
            message: '添加成功',
          });
        } else {
          this.$message({
            type: 'warning',
            message: '添加失败，请重试',
          });
        }
      } catch (error) {
        console.error('添加到购物车失败', error);
        this.$message({
          type: 'error',
          message: '添加失败，请检查网络连接',
        });
      } finally {
        this.dialogVisible = false; // 关闭对话框
      }
    },
    async fetchImage(productId) {
      try {
        const response = await axios.get(`/product/${productId}/image`, {
          responseType: 'blob', // 指定响应类型为 blob
        });

        if (response instanceof Blob) {
          const imageUrl = URL.createObjectURL(response);
          this.imageUrls.set(productId, imageUrl);
        } else {
          console.error('响应数据格式不正确:', response);
        }
      } catch (error) {
        console.error('获取图片失败', error);
      }
    },
    getImageUrl(productId) {
      return this.imageUrls.get(productId) || '';
    },
    pay(product) {
      const totalPrice = product.price * this.quantity; // 计算总价
      ElMessage.success(`购买成功，共支付${totalPrice}元`);
    },
  },
  mounted() {
    this.fetchProducts();
    this.fetchCategories(); // 获取类目数据
  },
};
</script>

<style scoped>
.productList {
  display: flex;
  justify-content: center;
  text-align: center;
  background: #eee;
}

.productList_box {
  background: white;
}

.category_list {
  width: 1150px;
  height: 50px;
}

.category {
  font-size: 16px;
  padding: 10px 30px;
  line-height: 50px;
}

.category:hover {
  color: #409EFF;
  border-bottom: 2px solid #409EFF;
  cursor: pointer;
}

.active {
  color: #409EFF;
  border-bottom: 2px solid #409EFF;
}

.product_box {
  width: 1150px;
}

.product_col {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  text-align: center;
}

.item {
  padding: 10px 15px;
  border: 2px #eeeeee solid;
  width: 200px;
}

.item:hover {
  box-shadow: 0 0 10px #ddd;
}

.cover {
  width: 200px;
  height: 200px;
}

.information {
  display: flex;
  justify-content: space-between;
  font-size: 16px;
  padding-top: 20px;
}

.pagination {
  text-align: center;
  padding: 30px 100px;
}
</style>



